package com.shipwe.loans.ui.activity

import android.os.Handler
import android.os.Looper
import android.view.View
import com.shipwe.loans.R
import com.shipwe.loans.databinding.ActivitySettingBinding
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.utils.dialog.UserDataClearDialog
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONArray
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/27 16:16
 * @Annotation：设置
 */
class ActivitySetting: ShipweActivity() {
    lateinit var binding: ActivitySettingBinding
    override fun getShipweRootView(): View {
        binding = ActivitySettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnVisibility(View.VISIBLE)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitle(getString(R.string.menu_setting))
    }

    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Setting Page")
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"Setting Page")
        }

        //清空用户数据
        binding.settingClearData.setOnClickListener {
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_DATA_CLEAR)
            //存在未结清的账单
            if (isUserSettingCheckUncleared()){
                showErrorTipsDialog(getString(R.string.user_data_clear_error),"Setting Page")
                return@setOnClickListener
            }
            showUserClearDataDialog()
        }

        //退出登录
        binding.settingLoginOut.setOnClickListener {
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_LOGINOUT,"")
            //退出登录，需要移除用户保存的信息
            ShipweSharedHelper.onShipweUserLoginOut()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(ActivityLogin::class.java)
            },300)
        }
    }

    override fun initShipweData() {
        //获取版本名称
        val packageInfo = packageManager.getPackageInfo(this.packageName, 0)
        val versionCode = packageInfo.versionCode // 版本号（整数）
        binding.settingVersion.text = String.format(getString(R.string.setting_version_name),packageInfo.versionName)

        //是否显示清空用户数据 (一直显示)
        val isShowClearData = CustomConfigsHelper.isShipweClearUserData()
        if (isShowClearData){
            binding.settingClearData.visibility = View.VISIBLE
        } else {
            binding.settingClearData.visibility = View.VISIBLE
        }
    }

    /**
     * 是否存在未结清的账单
     */
    private fun isUserSettingCheckUncleared(): Boolean{
        val pData = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_PRODUCT)
        if (pData.isNotEmpty()){
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                val status = item.optString("status")
                //存在 审核中、放款中 || 待还款
                if (status == "PENDING" || status == "REPAYMENT"){
                    return true
                }
            }
        }
        return false
    }

    /**
     * 清空用户数据dialog
     */
    private fun showUserClearDataDialog(){
        val clearDialog = UserDataClearDialog(this,object : UserDataClearDialog.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                submitUserClearDataAction()
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
    }

    /**
     * 清除用户数据
     */
    private fun submitUserClearDataAction(){
        showShipweLoading()
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.SHIPWE_API_USER_DATA_CLEAR_PATH)
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                dismissShipweLoading()
                //退出登录，需要移除用户保存的信息
                ShipweSharedHelper.onShipweUserLoginOut()
                onIntent(ActivityLogin::class.java)
            }
            override fun onRequestError(error: JSONObject) {
                showShipweToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                dismissShipweLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_USER_SETTING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_USER_SETTING_END)
    }
}